<template>
    <div>
        <div class="list">
            <!-- @load="getData" -->
            <van-list v-model="loading" :finished="finished"  class="movie-list">
                <van-cell @click="goComing(item)" v-for="(item, index) in movieList" :key="item.id" class="movie-card">
                    <div class="card-content">
                        <div class="names">
                            {{ item.cinema_name }}
                        </div>
                        <div class="addressInfo">
                            <div class="address">{{ item.address }}</div>
                            <div class="instance">{{ item.instance }}km</div>
                        </div>
                        <div class="phone">影院电话：{{ item.phone }}</div>
                        <div class="is_refund">
                            <div :style="{ color: x.color, borderColor: x.color }" v-for="(x, y) in item.tagList">{{
                                x.text }}
                            </div>
                        </div>
                    </div>
                </van-cell>
            </van-list>
        </div>
    </div>
</template>
<script>
import plantAPI from "@/api/plant";
import { getDistance } from 'geolib';
export default {
    data() {
        return {
            oldAllData: [],
            movieList: [],
            loading: true,
            finished: false,
            page: 1,
            isDataLoaded: false, // 数据加载状态
        }
    },
    watch: {

        region_id: {
            immediate: true,
            handler(newVal) {
                if (newVal && this.isDataLoaded) {
                    this.getregionData('region');
                }
            }
        },
        value2: {
            immediate: true,
            handler(newVal) {
                if (newVal && this.isDataLoaded) {
                    this.getregionData('instance');
                }
            }
        },
        value3: {
            immediate: true,
            handler(newVal) {
                if (newVal && this.isDataLoaded) {
                    this.getregionData('ticket');
                }
            }
        },

    },
    props: ["region_id", "value3", "value2", 'nums'],

    mounted() {
        this.getmovieTheater()
    },
    methods: {
        async getmovieTheater() {
            console.log(this.nums)
            this.loading = true;
            this.finished = false;
            this.isDataLoaded = false; // 重置加载状态

            try {
                let city_id = localStorage.getItem("city_id");
                const response = await plantAPI.getcinemaAPI(city_id);
                const data = JSON.parse(response.data.body).data;

                const tag = ['3D眼镜免费', '休息区', '改签', '艺术影厅', '可刷卡', '可停车', 'VIP厅'];
                this.movieList = data.map(item => {
                    item.instance = this.calculate(item.longitude, item.latitude);
                    const service = JSON.parse(item.service);
                    let tagList = [];
                    if (service) {
                        Object.keys(service).forEach((key) => {
                            let obj = {};
                            if (tag.includes(key)) {
                                obj.text = key;
                                obj.color = (key === '改签' || key === '艺术影厅' || key === 'VIP厅')
                                    ? "rgb(95, 224, 95)"
                                    : "#FFB433";
                                tagList.push(obj);
                            }
                        });
                    }
                    if (item.is_refund === 1) {
                        tagList.unshift({
                            text: '退',
                            color: "rgb(95, 224, 95)"
                        });
                    }
                    return {
                        ...item,
                        tagList
                    };
                });
                this.movieList = [...this.movieList].sort((a, b) => a.instance - b.instance)
                if (this.nums) {
                    this.movieList = this.movieList.splice(0, 10)
                }

                this.oldAllData = [...this.movieList];
                this.isDataLoaded = true; // 标记数据已加载完成



                // 数据加载完成后，检查是否有需要立即执行的筛选
                if (this.region_id) this.getregionData('region');
                if (this.value2) this.getregionData('instance');
                if (this.value3) this.getregionData('ticket');

            } catch (err) {
            } finally {
                this.loading = false;
                this.finished = true;
            }
        },

        getregionData(status) {
            if (!this.isDataLoaded) return;
            this.loading = true;
            switch (status) {
                case 'region':
                    if (this.region_id === 'a') {
                        this.movieList = [...this.oldAllData];
                    } else {
                        this.movieList = this.oldAllData.filter(item => item.region_id == this.region_id);
                    }
                    break;

                case 'instance':
                    this.movieList = (this.value2 == 'b')
                        ? [...this.oldAllData].sort((a, b) => a.instance - b.instance)
                        : [...this.oldAllData];
                    break;

                case 'ticket':
                    if (this.value3 == 'a') {
                        this.movieList = this.oldAllData.filter(item => item.is_refund == 1);
                    } else if (this.value3 == 'b') {
                        this.movieList = this.oldAllData.filter(item => item.is_refund != 1);
                    } else {
                        this.movieList = [...this.oldAllData];
                    }
                    break;

                default:
                    this.movieList = [...this.oldAllData];
            }

            this.loading = false;
            this.finished = true;
        },
        goComing(item) {
            this.$router.push({
                path: './comingTheater/movies',
                query: {
                    film_Info: JSON.stringify(item)
                }
            })
        },
        calculate(lon1, lat1) {
            let lon2 = localStorage.getItem('longitude')
            let lat2 = localStorage.getItem('latitude')
            if (lat1 && lon1 && lat2 && lon2) {
                const distanceInMeters = getDistance(
                    { latitude: parseFloat(lat1), longitude: parseFloat(lon1) },
                    { latitude: parseFloat(lat2), longitude: parseFloat(lon2) }
                );
                return (distanceInMeters / 1000).toFixed(2)
            }
        },
        getData() {
            // 模拟加载数据
            setTimeout(() => {
                if (this.page === 1) {
                    this.movies = [...this.mockMovies];
                } else {
                    // 加载更多数据，实际项目中这里会从API获取
                    const newMovies = this.mockMovies.map(movie => ({
                        ...movie,
                        id: movie.id + this.page * 10
                    }));
                    this.movies.push(...newMovies);
                }

                this.loading = false;
                if (this.page >= 3) {
                    this.finished = true;
                }
                this.page++;
            }, 500);
        }
    }
}

</script>
<style lang="scss" scoped>
.list:first-child {
    margin-top: 8px;
}

::v-deep .van-list {
    background: #F5F6F8 !important;
}

.movie-card {
    padding: 0 9px;
    margin-top: 8px;
    overflow: hidden;
    /* 新增 */
    background: #F5F6F8;

    .address,
    .phone {
        color: #5B626A;
        font-size: 13px;
        font-family: PingFang SC;
    }

    .is_refund {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        margin-top: 2px;

        >div {
            //display: flex;
            padding: 2px 3px 0 3px;
            //height: 20px;
            border-radius: 2px;
            line-height: 12px;
            height: 12px;
            font-size: 8px;
            border: 1px solid #000;
            margin-right: 5px;
        }
    }

    .card-content {
        //border-radius: 10px;
        background: #fff;
        //margin: 0 10px;
        padding: 10px;
        width: 100%;
        box-sizing: border-box;

        .names {
            height: 20px;
            line-height: 20px;
            font-family: PingFang SC;
            font-weight: 600;
            font-size: 14px;
            color: #1A1A1A;
            max-width: 100%; // 最大宽度（根据实际布局调整）
            white-space: nowrap; // 禁止换行
            overflow: hidden; // 隐藏溢出内容
            text-overflow: ellipsis; // 显示省略号
            display: inline-block; // 必须设置为块级元素才能生效
        }

        .addressInfo {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .address {
                flex-wrap: nowrap;
                margin-right: 10px;
                width: 280px;

                white-space: nowrap; // 禁止换行
                overflow: hidden; // 隐藏溢出内容
                text-overflow: ellipsis; // 显示省略号
                display: inline-block; // 必须设置为块级元素才能生效
            }

            .instance {
                color: #999999;
                font-size: 12px;
            }
        }


    }
}

/* 清除 van-cell 的干扰样式 */
::v-deep .van-cell {
    border-radius: 0 !important;
    padding: 0 !important;
    overflow: visible !important;
}
</style>
